﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Globalization;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using hdbankwebservice.DAO;
using hdbankwebservice.DTO;
namespace hdbankwebservice
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class HDBankWS : System.Web.Services.WebService
    {
        // tinh bang giay
        public static int timeOut = 600;

        // tinh bang %
        public static int ChuyenNoiNganHang = 1;
        public static int ChuyenLienNganHang = 2;
        public static int NhanTienLienNganHang = 3;

        public static int phanTramPhiGiaoDich;
        public static int phanTramMoiGioi = 30; // 

        //public int CardValid1()
        //{
        //    CardSystem.EMVServices ws = new CardSystem.EMVServices();
        //    ws.CookieContainer = new CookieContainer();
        //    string sid = ws.Authenticate("HDBank", "J9d5zvYrskK6DbJg");
        //    DateTime validfrom = new DateTime();
        //    DateTime validto = new DateTime();
        //    validfrom = DateTime.ParseExact("15/11/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture);
        //    validto = DateTime.ParseExact("05/12/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture);
        //    int i = ws.CardValid1(sid, "5103597136570421", 1, "6985A", "dang", validfrom, validto);
        //    return i;
        //}

        public int TransferMoneySameBank(string soTheGui, string soTheNhan, int soTienGui, int phiDichVu, int tinhphicualiennganhang)
        {
            int bTheGui = MineCardValid3(soTheGui);
            int bTheNhan = MineCardValid3(soTheNhan);
            int tongTien = 0;
            if (bTheGui != 0)
            {
                return -2; // thẻ gửi không hợp lệ
            }
            else if (bTheNhan != 0)
            {
                return -3; // thẻ người nhận không hợp lệ
            }
            else
            {
                TheTinDung ttdGui = TheTinDungDAO.LayThongTinThe(soTheGui);
                TaiKhoanKhachHang tkkhGui = TaiKhoanKhachHangDAO.LayThongTinTaiKhoan(ttdGui.KhachHang.SoTaiKhoan);
                if (KiemTraSoTienTrongTaiKhoan(tkkhGui, soTienGui) == true)
                {
                    TheTinDung ttdNhan = TheTinDungDAO.LayThongTinThe(soTheNhan);
                    TaiKhoanKhachHang tkkhNhan = TaiKhoanKhachHangDAO.LayThongTinTaiKhoan(ttdNhan.KhachHang.SoTaiKhoan);

                    ChuyenTien(tkkhGui, tkkhNhan, soTienGui, phiDichVu, tinhphicualiennganhang);
                    CapNhatChuyenTien(tkkhGui, tkkhNhan);
                    tongTien = soTienGui + (phiDichVu * soTienGui) / 100;
                    return tongTien;
                }
                else
                {
                    return 0; // tai khoan gui ko du tien 
                }
            }
        }

        private void CapNhatChuyenTien(TaiKhoanKhachHang tkgui, TaiKhoanKhachHang tknhan)
        {
            TaiKhoanKhachHangDAO.CapNhatTaiKhoanKhachHang(tkgui);
            TaiKhoanKhachHangDAO.CapNhatTaiKhoanKhachHang(tknhan);
        }

        private void ChuyenTien(TaiKhoanKhachHang tkgui, TaiKhoanKhachHang tknhan, int sotiengui, int phidichvu, int tinhphicualiennganhang)
        {
            int tongtien = (phidichvu * sotiengui) / 100 + sotiengui;
            if (TaiKhoanLaNganHangGui(tkgui.SoTaiKhoan) == true)
            {
                tkgui.SoTienGoc = tkgui.SoTienGoc - tongtien;
            }
            else
            {
                if (tkgui.SoTienGoc >= tongtien)
                {
                    tkgui.SoTienGoc = tkgui.SoTienGoc - tongtien;
                }
                else
                {
                    tkgui.SoTinDungConLai = tkgui.SoTinDungConLai + tkgui.SoTienGoc - tongtien;
                    tkgui.SoTienGoc = 0;
                }
            }
            tknhan.SoTienGoc += sotiengui + tinhphicualiennganhang; //tinhphicualiennganhang = 0 la kh thuong
        }

        private bool KiemTraSoTienTrongTaiKhoan(TaiKhoanKhachHang TK, int AmountMoney)
        {
            if (TaiKhoanLaNganHangGui(TK.SoTaiKhoan))
            {
                return true;
            }
            if (TK.SoTienGoc + TK.SoTinDungConLai >= AmountMoney)
                return true;
            return false; // khong du tien
        }

        private bool TaiKhoanLaNganHangGui(string soTaiKhoan)
        {
            int maNhomKhachHang = TaiKhoanKhachHangDAO.LayThongTinNhomKhachHang(soTaiKhoan);
            if (maNhomKhachHang == 1 || maNhomKhachHang == 2)
                return true;
            return false;
        }

        public int MineCardValid3(string CreditCardID)
        {
            CardSystem.EMVServices ws = new CardSystem.EMVServices();
            ws.CookieContainer = new CookieContainer();
            string sid = ws.Authenticate("HDBank", "J9d5zvYrskK6DbJg");
            TheTinDung the = TheTinDungDAO.LayThongTinThe(CreditCardID);
            int kq = 0;
            if (the != null)
            {
                kq = ws.CardValid3(sid, the.SoThe, the.MaNhomThe, the.KhachHang.HoTen);
            }
            else
            {
                kq = -2; // the khong hợp lệ, mặc định ngầm bên dưới do ko có trong csdl
            }
            //int kq = ws.CardValid3(sid, "5108247571535829",1, "seabank");
            return kq;
        }

        //cần sửa lại
        private int TranferMoneyDiffBank(string soTheGui, string soTheNhan, int soTienGui, LienKetNganHang nganhangban)
        {
            int kq = -1;
            string sothenganhangban = TheTinDungDAO.LaySoTheTinDung(nganhangban.MaKhachHang);
            int tongTienChuyenLienNganHang = ChuyenTienChoNganHangBan(soTheNhan, soTheGui, nganhangban, soTienGui);

            if (tongTienChuyenLienNganHang >= soTienGui)
            {
                phanTramPhiGiaoDich = PhiGiaoDichDAO.LayPhiHienHanh(ChuyenLienNganHang, nganhangban.TenNganHang);
                int philiennganhang = tongTienChuyenLienNganHang - soTienGui;
                int kq1 = TransferMoneySameBank(soTheGui, sothenganhangban, soTienGui, phanTramPhiGiaoDich, philiennganhang);
                if (kq1 > 0)
                {
                    kq = kq1;
                }
            }
            else
            {
                // chuyen tien khong thang cong
                kq = tongTienChuyenLienNganHang;
            }
            return kq;
        }

        private int ChuyenTienChoNganHangBan(string strCardIDReceive, string strCardIDSend, LienKetNganHang nganhangban, int iAmount)
        {
            int kq = -1;
            //string sid = (string)WSProxy.CallWebService(nganhangban.URL, nganhangban.TenWebservice, "Login", new object[] { nganhangban.UserName, nganhangban.Password });
            //kq = (int)WSProxy.CallWebService(nganhangban.URL, nganhangban.TenWebservice, "Withdraw", new object[] { sid, strCardIDReceive, strCardIDSend, iAmount });
            switch (nganhangban.TenNganHang)
            {
                case "MSB":
                    MaritimeBankWS.ServiceMaritimeBank wsbankMB = new MaritimeBankWS.ServiceMaritimeBank();
                    //wsbankMB.Url = "http://aspspider.info/fujishidou/ServiceMaritimeBank.asmx";
                    wsbankMB.Url = nganhangban.URL;
                    wsbankMB.CookieContainer = new CookieContainer();
                    string sidMB = wsbankMB.Login(nganhangban.UserName, nganhangban.Password);
                    kq = wsbankMB.Withdraw(sidMB, strCardIDReceive, strCardIDSend, iAmount);
                    return kq;
                case "NAB":
                    NamABankWS.Service1 wsbankNA = new NamABankWS.Service1();
                    wsbankNA.Url = nganhangban.URL;
                    wsbankNA.CookieContainer = new CookieContainer();
                    string sidNA = wsbankNA.Login(nganhangban.UserName, nganhangban.Password);
                    kq = wsbankNA.Withdraw(sidNA, strCardIDReceive, strCardIDSend, iAmount);
                    return kq;
                default:
                    return kq;
            }
        }

        [WebMethod]
        public int Withdraw(string SID, string creditCardReceive, string creditCardSend, int amountMoney)
        {
            // do su dung ham nay tức thẻ nhận phải là của ngân hàng HDB
            int kq = 0;
            if (SIDChecker(SID))
            {
                CardSystem.EMVServices ws = new CardSystem.EMVServices();
                string tennganhanggui = ws.GetBankCommercialNameOfCreditCard(creditCardSend);

                LienKetNganHang nganhanggui = LienKetNganHangDAO.LayThongTinNganHangLienKet(tennganhanggui);
                string sothenganhangban = TheTinDungDAO.LaySoTheTinDung(nganhanggui.MaKhachHang);

                string tennganhangnhan = ws.GetBankCommercialNameOfCreditCard(creditCardReceive);
                if (tennganhangnhan == "HDB")
                {

                    phanTramPhiGiaoDich = PhiGiaoDichDAO.LayPhiHienHanh(NhanTienLienNganHang, nganhanggui.TenNganHang);
                    kq = TransferMoneySameBank(sothenganhangban, creditCardReceive, amountMoney, phanTramPhiGiaoDich, 0);
                }
                else
                {
                    kq = -2;// the nhan khong le
                }
            }
            else
            {
                kq = -1; // chưa đăng nhập
            }
            return kq;
        }

        [WebMethod]
        public string Login(string userName, string password)
        {
            string kq = "Fail";
            Users us = UserDAO.Login(userName, MineUtils.HashPass(userName, password));
            if (us != null)
            {
                if (us.MaNhomKhachHang == 1 || us.MaNhomKhachHang == 2)
                {
                    SIDDTO sid = SIDDAO.LaySIDDTO(userName);
                    if (sid != null && KiemTraTimeOut(sid.SID) == true) // co trong csdl va chua het timeout
                    {
                        kq = sid.SID;
                    }
                    else
                    {
                        kq = MineUtils.SIDGenerate();
                        SIDDAO.ThemSID(kq, userName);
                    }
                }
                else
                {
                    kq = "Not permission"; // khong phai la moi gioi hoac ngan hang
                }
            }
            else
            {
                kq = "Not permission"; // sai username hoặc password
            }
            return kq;
        }

        [WebMethod]
        public int Tranfer(string SID, string creditCardSend, string creditCardReceive, int amountMoney)
        {
            // Kiem tra the nhan co cung ngan hang ko
            int kq = -1;
            if (KiemTraTienGui(amountMoney) == true)
            {
                if (SIDChecker(SID))
                {
                    CardSystem.EMVServices ws = new CardSystem.EMVServices();
                    string tennganhangthegui = ws.GetBankCommercialNameOfCreditCard(creditCardSend);/// lay tu cardsystem truyen tham so tu the strCardIDSend
                    string tennganhangthenhan = ws.GetBankCommercialNameOfCreditCard(creditCardReceive);// lay tu cardsystem truyen tham so tu the strCardIDReceive
                    // viet kiem tra hop cua the co phai la cardnotexit
                    if (tennganhangthegui == "CardNotExist" || tennganhangthenhan == "CardNotExist")
                    {
                        kq = -11; // card not exist
                    }
                    else
                    {
                        if (tennganhangthenhan == tennganhangthegui)
                        {
                            // Same Bank
                            phanTramPhiGiaoDich = PhiGiaoDichDAO.LayPhiHienHanh(ChuyenNoiNganHang, tennganhangthenhan);
                            kq = TransferMoneySameBank(creditCardSend, creditCardReceive, amountMoney, phanTramPhiGiaoDich, 0);

                        }
                        else
                        {
                            LienKetNganHang nganhangban = LienKetNganHangDAO.LayThongTinNganHangLienKet(tennganhangthenhan);
                            if (nganhangban != null) // khac ngan hang
                            {
                                //Diff Bank
                                kq = TranferMoneyDiffBank(creditCardSend, creditCardReceive, amountMoney, nganhangban);
                            }
                            else
                            {
                                // khong co lien ket nganh hang nhan
                                kq = -10;
                            }
                        }
                        // cong tien cho moi gioi phi dich vu
                        // 30% cua phidichvu
                        HoaHongCuaMoiGioi(SID, phanTramPhiGiaoDich, amountMoney);
                    }
                }
                else
                {
                    kq = -1; //chưa đăng nhập
                }
            }
            else
            {
                kq = -5; // so tien ko hop le
            }
            return kq;
        }

        private void HoaHongCuaMoiGioi(string SID, int phidichvu, int sotiengui)
        {
            string username = SIDDAO.LayUserName(SID);
            Users moigioi = UserDAO.LayThongTinUser(username);
            TaiKhoanKhachHang tkmoigioi = TaiKhoanKhachHangDAO.LayThongTinTaiKhoan("", moigioi.MaKhachHang);
            int sotienhoahong = (((sotiengui * phidichvu) / 100) * phanTramMoiGioi) / 100;
            tkmoigioi.SoTienGoc += sotienhoahong;
            TaiKhoanKhachHangDAO.CapNhatTaiKhoanKhachHang(tkmoigioi);
        }

        private bool KiemTraTienGui(int soTienGui)
        {
            if (soTienGui % 1000 == 0)
                return true;
            return false;
        }

        public bool SIDChecker(string SIDString)
        {
            bool kq = false;
            string SID = SIDDAO.LaySID(SIDString);
            if (SID != "") // co ton tai SID
            {
                kq = KiemTraTimeOut(SID);
            }
            return kq;
        }

        public bool KiemTraTimeOut(string SID)
        {
            bool kq = false;
            byte[] btimout = MineUtils.StringToByteArray(SID);
            string stimeout = MineUtils.GiaiMa(btimout);
            DateTime dtime = DateTime.Parse(stimeout);
            TimeSpan ts = DateTime.Now - dtime;
            if (ts.TotalSeconds < timeOut)
            {
                kq = true; // con timeout
            }
            else // het timeout nhg co trong csdl
            {
                SIDDAO.XoaSID(SID);
            }
            return kq;
        }
    }
}